﻿using AutoMapper;
using AutoMapper.Internal.Mappers;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ProductionManage.Models.Products;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime;
using System.Text;
using System.Threading.Tasks;
using test.demo.Model.WM仓储管理;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using wangyaxin.Models;
using wangyaxin.Wang.Dto;
using wangyaxin.Wyx.Dto;

namespace wangyaxin.Wyx
{
    [ApiExplorerSettings(GroupName = "王亚鑫")]
    public class WyxAppService: ApplicationService, IWyxAppService
    {
        private readonly IRepository<Product,int> _ProductRepository;
        private readonly IRepository<ProductType, int> _ProductTypeRepository;
        private readonly IMapper _mapper; // 依赖注入 IMapper

        public WyxAppService(IRepository<Product,int> productRepository,    IRepository<ProductType, int> productTypeRepository, IMapper mapper)
        {
            _ProductRepository = productRepository; 
            _ProductTypeRepository = productTypeRepository;
            _mapper = mapper;
        
        }



        /// <summary>
        /// 获取产品列表--王亚鑫
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetProduct(string? ProductName,string? ProductCode,int pageIndex , int pageSize )
        {

           

            var wang = await _ProductRepository.ToListAsync();
            if(!string.IsNullOrEmpty(ProductName))
            {
                wang = wang.Where(x => x.ProductName.Contains(ProductName)).ToList();
            }
            if (!string.IsNullOrEmpty(ProductCode))
            {
                wang = wang.Where(x => x.ProductCode==ProductCode).ToList();
            }
            var user = ObjectMapper.Map<List<Product>, List<ProductDto>>(wang);
            var list = wang.Count();
            var pageCount = (int)Math.Ceiling(list *  (pageIndex + 1.0)/pageSize);
            return JsonConvert.SerializeObject(new PageDto<ProductDto> { code = "", data = user, msg = "", count = user.Count });

        }

        /// <summary>
        /// 添加产品--王亚鑫
        /// </summary>
        /// <param name="input">产品数据传输对象</param>
        /// <returns></returns>
      
        public async Task<string> AddProduct(CreateProductDto input)
        {

            var pro = new Product
            {
                ProductName = input.ProductName,
                ProductCode= input.ProductCode,
                UnitName=input.UnitName,
                ProductItem=input.ProductItem,
                ProductTypeId = input.ProductTypeId,
                IsEnable=input.IsEnable,
                IsStock=input.IsStock,
                Remark=input.Remark,
            };

            // 将产品添加到数据库
            await _ProductRepository.InsertAsync(pro);
            // 将DTO映射到实体
            var product = ObjectMapper.Map<Product, ProductDto>(pro);

            // 返回成功响应
            return JsonConvert.SerializeObject(new PageDto<ProductDto>

            {
                code = "", // 可以根据需要设置状态码
                data = new List<ProductDto> { product }, // 返回添加的用户信息
                msg = "添加成功", // 可以根据需要添加消息
                count = 1 // 添加的用户数量
            });

       


        }

        /// <summary>
        /// 删除产品--王亚鑫
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteProduct(int id)
        {
            await _ProductRepository.DeleteAsync(id);
        }

        /// <summary>
        /// 反填产品--王亚鑫
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Product> GetProductById(int id)
        {
            var wang = await _ProductRepository.GetAsync(c=>c.Id==id);
            return wang;
        }

        /// <summary>
        /// 更新产品--王亚鑫
        /// </summary>
        /// <param name="id">产品ID</param>
        /// <param name="product">待更新的产品信息</param>
        /// <returns></returns>
      
        public async Task<string> UpdateProduct(UpdateProductDto product)
        {

            var result = await _ProductRepository.GetAsync(c => c.Id == product.Id);
            result.ProductName = product.ProductName;
            result.ProductCode = product.ProductCode;
            result.IsEnable = product.IsEnable;
            result.IsStock=product.IsStock;
            result.SpecifiCation=product.SpecifiCation;
            result.UnitName=product.UnitName;
            result.Remark=product.Remark;
            await _ProductRepository.UpdateAsync(result);


            //var existingProduct = ObjectMapper.Map<UpdateProductDto,Product>(product);
            return JsonConvert.SerializeObject(new PageDto<UpdateProductDto>
            {
                code = "200",
                data = null,
                msg = "更新成功",
                count = 0
            });
        }

        /// <summary>
        /// 获取产品类型Tree--王亚鑫
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>

        [HttpGet, Route("GetProductType")]
        public async Task<List<object>> GetProductType(int parentId = 0)
        {
            // 获取所有产品类型
            var wang = await _ProductTypeRepository.ToListAsync();

            // 过滤出当前父级的产品类型
            var result = new List<object>();

            foreach (var c in wang.Where(x => x.PId == parentId))
            {
                var child = new
                {
                    Value = c.Id,
                    Label = c.TypeName,
                    ParentId = c.PId,
                    // 递归异步调用以获取子产品类型
                    Children = await GetProductType(c.Id) // 使用await获取结果
                };

                result.Add(child);
            }

            return result;
        }

        
    }
}
